package com.mju.controller;

import com.mju.controller.common.BaseController;
import com.mju.controller.common.JsonResult;
import com.mju.service.ICartService;
import com.mju.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/carts")
public class CartController extends BaseController {
    @Autowired
    private ICartService cartService;

    @PostMapping("/add_to_cart")
    public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Map<String, String> map = parseTokenGetUidAndUname(token);
        String uid = map.get("uid");
        String uname = map.get("uname");
        cartService.addToCart(
                Integer.valueOf(uid),
                pid,
                amount,
                uname
        );
        return new JsonResult<Void>(OK);
    }

    @GetMapping
    public JsonResult<List<CartVO>> getVOByUid(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String uid = parseTokenGetUid(token);
        List<CartVO> data = cartService.getVOByUid(Integer.valueOf(uid));
        return new JsonResult<>(OK, data);
    }

    @GetMapping("/{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Map<String, String> map = parseTokenGetUidAndUname(token);
        String uid = map.get("uid");
        String uname = map.get("uname");

        Integer data = cartService.addNum(cid, Integer.parseInt(uid), uname);
        return new JsonResult<>(OK, data);
    }

    @GetMapping("/{cid}/num/sub")
    public JsonResult<Integer> subNum(@PathVariable("cid") Integer cid, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Map<String, String> map = parseTokenGetUidAndUname(token);
        String uid = map.get("uid");
        String uname = map.get("uname");

        Integer data = cartService.subNum(cid, Integer.parseInt(uid), uname);
        return new JsonResult<>(OK, data);
    }

    @GetMapping("/list")
    public JsonResult<List<CartVO>> selectVOByCids(Integer[] cids, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String uid = parseTokenGetUid(token);
        List<CartVO> data = cartService.getVOByCids(Integer.valueOf(uid), cids);
        return new JsonResult<>(OK, data);
    }
    //处理根据cids内的指定cid删除cart的请求
    @GetMapping("/deleteCart")
    public JsonResult<Void> deleteCartByCid(Integer[] cids){
        //遍历执行删除操作
        for (Integer cid: cids) {
            cartService.deleteCartByCid(cid);
        }
        return new JsonResult<>(OK);
    }
}
